package outman.weibo.ui;

import java.net.MalformedURLException;
import java.net.URL;

import outman.weibo.R;
import outman.weibo.WeiboDialogListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

public class WeiboDialog extends Dialog {

    private static final String TAG = "WeiboDialog";

    private String url;

    private ProgressDialog progressDialog;
    private RelativeLayout mContent;
    private RelativeLayout webViewContainer;
    private WebView mWebView;

    // LoginActivity传过来的listener用于监视授权状态是否完成（观察者）
    private WeiboDialogListener listener;

    public WeiboDialog(Context context, String url, WeiboDialogListener listener) {
	super(context, R.style.ContentOverlay);
	this.url = url;
	this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	progressDialog = new ProgressDialog(getContext());
	progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	progressDialog.setMessage("Loading...");

	// 设置弹出装webview的对话框为无标题的形式
	requestWindowFeature(Window.FEATURE_NO_TITLE);

	mContent = new RelativeLayout(getContext());
	setUpWebView();

	addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT,
		LayoutParams.FILL_PARENT));

	Log.i(TAG, "haha");

    }

    private void setUpWebView() {
	webViewContainer = new RelativeLayout(getContext());

	mWebView = new WebView(getContext());
	// 默认情况下时可以看到滚动条的
	mWebView.setVerticalScrollBarEnabled(false);
	mWebView.setHorizontalScrollBarEnabled(false);
	mWebView.getSettings().setJavaScriptEnabled(true);
	mWebView.setWebViewClient(new WeiboWebViewClient());

	// webview加载授权页面的url
	mWebView.loadUrl(url);

	// 使webview沾满它的容器
	LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
		LayoutParams.FILL_PARENT);
	mWebView.setLayoutParams(params);
	mWebView.setVisibility(View.INVISIBLE);

	webViewContainer.addView(mWebView);

	// 设置放webview容器的布局参数
	RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
		LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

	Resources resources = getContext().getResources();
	rLp.leftMargin = resources
		.getDimensionPixelSize(R.dimen.dialog_left_margin);
	rLp.rightMargin = resources
		.getDimensionPixelSize(R.dimen.dialog_right_margin);
	rLp.topMargin = resources
		.getDimensionPixelSize(R.dimen.dialog_top_margin);
	rLp.bottomMargin = resources
		.getDimensionPixelSize(R.dimen.dialog_bottom_margin);
	mContent.addView(webViewContainer, rLp);

    }

    private class WeiboWebViewClient extends WebViewClient {
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {

	    Log.i(TAG, "on page started url : " + url);

	    if (url.startsWith("http://127.0.0.1")) {
		handleRedirectUrl(view, url);
		view.stopLoading();
		WeiboDialog.this.dismiss();

		return;
	    }

	    super.onPageStarted(view, url, favicon);

	    progressDialog.show();
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
	    Log.i(TAG, "Redirect URL: " + url);

	    handleRedirectUrl(view, url);

	    // 获取到了access token准备进入MainTabs,隐去对话框
	    WeiboDialog.this.dismiss();

	    return true;
	}

	private void handleRedirectUrl(WebView view, String url) {

	    try {

		Bundle values = new Bundle();

		URL u = new URL(url);

		Log.i(TAG, u.toString());

		String query = u.getQuery();

		Log.i(TAG, "query: " + query);

		if (null != query) {

		    String[] arrays = query.split("&");

		    for (String array : arrays) {
			String[] temp = array.split("=");
			values.putString(temp[0], temp[1]);
		    }
		}

		String ref = u.getRef();

		if (null != ref) {
		    String[] arrays2 = ref.split("&");

		    for (String array : arrays2) {
			String[] temp = array.split("=");
			values.putString(temp[0], temp[1]);
		    }
		}

		listener.onComplete(values);

	    } catch (MalformedURLException e) {
		e.printStackTrace();
	    }
	}

	@Override
	public void onPageFinished(WebView view, String url) {
	    Log.i(TAG, "onPageFinished URL: " + url);
	    super.onPageFinished(view, url);
	    // 页面加载完成则关闭进度圈
	    progressDialog.dismiss();

	    mContent.setBackgroundColor(Color.TRANSPARENT);

	    // 显示加载好的webview
	    mWebView.setVisibility(View.VISIBLE);
	}
    }

}
